// =====================================================================================
//	Copyright (C) 2018 by Jiaxing Shao.All rights reserved.
//	文 件 名:  main.cpp
//	作    者:  Jiaxing Shao, 13315567369@163.com
//	版 本 号:  1.0
//	创建时间:  2018年08月15日 10时35分42秒
//	Compiler:  g++
//	描    述:
// =====================================================================================

#include "TinyXmlDocument.h"
#include "TinyXmlElement.h"

#include <chrono>
#include <iostream>
#include <memory>

using namespace std;
using namespace chrono;
using namespace tinyxml2;

void encode(const char *filename);
void decode(const char *filename);

int main(int argc, char *argv[])
{
    string filename = "test.xml";
    auto   start    = std::chrono::high_resolution_clock::now();
    encode(filename.c_str());
    auto end      = std::chrono::high_resolution_clock::now();
    auto duration = duration_cast<microseconds>(end - start);
    cout << "encode 消耗时间(us): " << duration.count() << endl;

    decode(filename.c_str());
    return 0;
}

void encode(const char *filename)
{
    cout << "*******************" << endl;
    xmlutils::TinyXmlDocument doc;
    doc.addDeclaration();
    auto root = doc.addRootElement("school");
    root->setAttribute("name", "山东蓝翔");
    auto teacher1 = root->addSubElement("teacher");
    teacher1->setText("张三");
    teacher1->setAttribute("age", 30);

    auto teacher2 = root->addSubElement("teacher", "李四");
    teacher2->setAttribute("age", 35);

    string xmlStr = doc.toXmlString();
    cout << xmlStr << endl;
    doc.saveXmlFile(filename);
    cout << "*******************" << endl;
}

void decode(const char *filename)
{
    xmlutils::TinyXmlDocument doc(filename);
    if (!doc.parseSuccess()) {
        cout << "XML解析失败!!!" << endl;
    }
    auto root = doc.getRootElement();

    cout << "*******************" << endl;
    cout << "root value: " << root->getTagName() << endl;
    auto child = root->getSubElement();
    cout << "child value: " << child->getTagName() << endl;
    cout << "child text: " << child->getText() << endl;
    cout << "child attr: " << child->getIntAttribute("age") << endl;

    auto next = child->getNextElement();
    cout << "next value: " << next->getTagName() << endl;
    cout << "next text: " << next->getText() << endl;
    cout << "next attr: " << next->getIntAttribute("age") << endl;
    root->setTagName("hello");

    cout << "*******************" << endl;
    cout << doc.toXmlString() << endl;
    cout << "*******************" << endl;
}
